

#include <gfx/polyrendermesh.h>

inka::gfx::PolyRenderMesh::PolyRenderMesh()
  : _numberOfVertices(0)
  , _vertices(0)
  , _normals(0)
  , _texCoords(0)
  , _selections(0)
  , _numberOfIndices(0)
  , _indices(0)
{
}


void inka::gfx::PolyRenderMesh::SetVertices(unsigned num, VertexBuffer *vertices, VertexBuffer *normals, VertexBuffer *texCoords)
{
  _numberOfVertices = num;
  _vertices = vertices;
  _normals = normals;
  _texCoords = texCoords;
}

void inka::gfx::PolyRenderMesh::SetSelections(VertexBuffer *selections)
{
  _selections = selections;
}

inka::gfx::VertexBuffer* inka::gfx::PolyRenderMesh::GetSelections()
{
  return _selections;
}

void inka::gfx::PolyRenderMesh::SetIndices(unsigned num, IndexBuffer *indices)
{
  _numberOfIndices = num;
  _indices = indices;
}


void inka::gfx::PolyRenderMesh::Render()
{
  _vertices->Bind();
  glEnableClientState(GL_VERTEX_ARRAY);
  glVertexPointer(3, GL_FLOAT, 3*sizeof(float), 0);

  if (_normals)
    {
      _normals->Bind();
      glEnableClientState(GL_NORMAL_ARRAY);
      glNormalPointer(GL_FLOAT, 3*sizeof(float), 0);
    }
  else
    {
      glDisableClientState(GL_NORMAL_ARRAY);
    }

  if (_selections)
    {
      _selections->Bind();
      glClientActiveTexture(GL_TEXTURE2);
      glEnableClientState(GL_TEXTURE_COORD_ARRAY);
      glTexCoordPointer(1, GL_FLOAT, sizeof(float), 0);
    }
  else
    {
      glClientActiveTexture(GL_TEXTURE2);
      glDisableClientState(GL_TEXTURE_COORD_ARRAY);
    }

  if (_texCoords)
    {
      _texCoords->Bind();
      glClientActiveTexture (GL_TEXTURE0);
      glEnableClientState(GL_TEXTURE_COORD_ARRAY);
      glTexCoordPointer(2, GL_FLOAT, 2*sizeof(float), 0);
    }
  else
    {
      glClientActiveTexture(GL_TEXTURE0);
      glDisableClientState(GL_TEXTURE_COORD_ARRAY);
    }


  _indices->Bind();
  glDrawElements(GL_TRIANGLES, _numberOfIndices, GL_UNSIGNED_INT, 0);


  glDisableClientState(GL_VERTEX_ARRAY);
  if (_normals)
    {
      glDisableClientState (GL_NORMAL_ARRAY);
    }
  if (_selections)
    {
      glClientActiveTexture(GL_TEXTURE2);
      glDisableClientState (GL_TEXTURE_COORD_ARRAY);
    }
  if (_texCoords)
    {
      glClientActiveTexture(GL_TEXTURE0);
      glDisableClientState (GL_TEXTURE_COORD_ARRAY);
    }
}
